import { useState } from "react";
import { useReactive } from "ahooks";
import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, Picker, View } from "@tarojs/components";

import ByTag from "@/components/ui/ByTag";
import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import ByIcon from "@/components/ui/ByIcon";
import ByText from "@/components/ui/ByText";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import PopupQuota from "./components/PopupQuota";
import Uploader from "@/components/app/Uploader";
import FormInput from "@/components/common/FormInput";
import ByStepsItem from "@/components/ui/ByStepsItem";
import ByCellGroup from "@/components/ui/ByCellGroup";
import PopupMember from "@/components/app/PopupMember";
import ByImageGroup from "@/components/ui/ByImageGroup";
import PopupShop from "../material/components/PopupShop";
import CustomerCard from "@/components/app/CustomerCard";
import TagRadioGroup from "@/components/app/TagRadioGroup";
import FormInputNumber from "@/components/common/FormInputNumber";
import {
  DetailMaterialItem,
  DetailQuotaItem,
} from "./components/BudchgDetailItem";


import ApiCrm from "@/api/crm";
import ApiWorkflow from "@/api/workflow";

import useAppStore from "@/store";
import useForm from "@/hooks/useForm";
import useFetch from "@/hooks/useFetch";
import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";

import { IntentCustomerData } from "@/types/customer";

import { TaskDetail } from "@/types/global";
import { enumReportTypeOptions } from "@/packageProject/utils/enum";

// 定额/材料 明细项
export type DudchgDetailItem = {
  // 自定义
  _id: number;

  /**
   * 类型 0、定额 1、材料 2、费用 3、定额包
   */
  detailType: number;
  materialCode: string;
  materialId: number;
  materialName: string;
  materialNum: number;
  materialSalePrice: number;
  materialSpec: string;
  materialUnit: string;
  buyPrice: number;
  /**
   * 材料成本
   */
  materialCost: string;

  quotaCode: string;
  quotaId: number;
  quotaName: string;
  quotaNum: number;
  /**
   * 综合价
   */
  quotaPrice: number;
  quotaUnit: string;
  /**
   * 承包价
   */
  contractPrice: number;
  // [property: string]: any;
};

//  承担人信息
type Undertaker = {
  /**
   * 自定义
   */
  _id?: number;
  /**
   * 承担金额
   */
  amount: number;
  supplyCode?: string;
  /**
   * 供应商ID（当type=1时必填）
   */
  supplyId?: number;
  supplyName?: string;
  /**
   * 承担类型：0:施工人员,1:供应商，2:工人
   */
  type: number;
  userCode?: string;
  /**
   * 用户ID（当type=0时必填）
   */
  userId?: number;
  userName?: string;
  [property: string]: any;
};

// 承担人项
const UndertakersItem = ({
  source,
  showRemove,
  onRemove,
  onPicker,
}: {
  source: Undertaker;
  showRemove?: boolean;
  onRemove: () => void;
  onPicker: (model: Undertaker) => void;
}) => {
  // 承担类型：0:施工人员,1:供应商，2:工人
  const model = useReactive(source);
  const text = model.type === 1 ? model.supplyName : model.userName;

  return (
    <ByRow>
      <ByCol span={6}>
        <ByCell label="承担人" vertical className="mr-2">
          <FormInput
            disabled
            value={text}
            placeholder="请选择"
            suffix={<ByIcon name="ArrowBottom" />}
            onClick={() => onPicker(model)}
          />
        </ByCell>
      </ByCol>
      <ByCol span={5}>
        <ByCell label="承担金额" vertical>
          <FormInputNumber
            prefix="¥"
            precision={2}
            placeholder="输入金额"
            defaultValue={model.amount}
            onChange={(e) => (model.amount = e)}
          />
        </ByCell>
      </ByCol>
      <ByCol span={1} className="pt-[100px] text-right">
        {showRemove && (
          <ByIcon name="Remove" className="text-error" onClick={onRemove} />
        )}
      </ByCol>
    </ByRow>
  );
};

function createUndertaskerItem() {
  return {
    _id: +new Date(),
  } as Undertaker;
}

const BudchgDetailsItem = ({
  source,
  onRemove,
}: {
  source: DudchgDetailItem;
  onRemove: () => void;
}) => {
  const { detailType } = source;

  const RenderNode = detailType === 1 ? DetailMaterialItem : DetailQuotaItem;

  return (
    <ByRow align="center">
      <ByCol span={11}>
        <RenderNode source={source} />
      </ByCol>

      <ByCol span={1} className="text-right">
        <ByIcon name="Remove" className="text-error" onClick={onRemove} />
      </ByCol>
    </ByRow>
  );
};

export default () => {
  const { params } = useRouter();

  const workflowInstanceId = Number(params.wl_id || 0);
  const intentCustomerId = Number(params.intentCustomerId);
  const workFlowDefinitionId = Number(params.workFlowDefinitionId || 0);
  // 编辑模式：存在masterId，表示编辑
  const masterId = decodeURIComponent(params.masterId || '');

  // 客户信息
  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res: any) => res.intentCustomer,
  });

  // 定额/材料列表
  const budchgDetails = useReactive<DudchgDetailItem[]>([]);

  // 承担人列表
  const undertakers = useReactive<Undertaker[]>([createUndertaskerItem()]);

  // 提交数据
  const { loading, model, setModel, submit } = useForm<{
    budchgDetails: DudchgDetailItem[];
    undertakers: Undertaker[];
    intentCustomerId: number;
    penaltyType: string;
    description: string;
    remark: string;
    type: number;
    /**
     * 附件
     */
    files: string[];

    amount: number;
    workFlowDefinitionId: number;

    masterId?: string
  }>(ApiWorkflow.signReport, {
    method: masterId ? "PUT" : "POST",
    defaultModel: {
      type: 1,
      remark: "",
      penaltyType: "中期款承担",
      budchgDetails,
      undertakers,
      intentCustomerId,
      files: [],
      masterId,
    },
    rules: {
      undertakers: {
        type: "array",
        defaultField: {
          validator(rule, value, callback) {
            const index = Number(rule.field) + 1;
            const { type, userId, supplyId, amount } = value;

            if ((type === 1 && !supplyId) || !userId) {
              return callback(`第${index}项未选择承担人`);
            }

            if (!amount) {
              return callback(`第${index}项未填写金额`);
            }
            callback();
          },
        },
      },
      budchgDetails: {
        type: "array",
        defaultField: {
          validator(rule, value, callback) {
            const index = Number(rule.field) + 1;
            const { detailType, quotaId, materialId } = value;

            if (detailType == 0 && !quotaId) {
              return callback(`第${index}项未选择定额内容`);
            }

            if (detailType == 1 && !materialId) {
              return callback(`第${index}项未选择材料`);
            }

            callback();
          },
        },
      },
      workFlowDefinitionId: { required: true, message: "请选择审批流程" },
    },
    onSuccess() {
      Taro.showToast({ title: "提交成功" });
      Taro.redirectTo({
        url: `/packageProject/pages/success/index?intentCustomerId=${intentCustomerId}&title=签报成功`,
      });
    },
  });

  // 类型 0、定额 1、材料 2、费用 3、定额包
  const [quoteType, setQuoteType] = useState(-1);

  const chooseQuoteType = async () => {
    const { tapIndex } = await Taro.showActionSheet({
      alertText: "选择类型",
      itemList: ["定额", "材料"],
    });
    setQuoteType(tapIndex);
  };

  // 定额选择确认
  const pickerQuotaChange = (e) => {
    // detailType
    // 类型 0、定额 1、材料 2、费用 3、定额包

    const obj: Record<string, any> = { _id: new Date(), detailType: quoteType };

    if (quoteType === 1) {
      // 材料
      obj.materialNum = e.Num;
      obj.materialSpec = e.Spec;
      // obj.materialSalePrice = e.BuyPrice;
      obj.materialSalePrice = e.MaterialPrice;
      obj.materialId = e.MaterialId;
      obj.materialCode = e.MatchCode;
      obj.materialName = e.MaterialName;
      obj.materialUnit = e.MaterialUnit;
    } else {
      // 定额
      obj.quotaNum = e.QuotaNum;
      obj.quotaUnit = e.Unit;
      obj.quotaId = e.QuotaId;
      obj.quotaCode = e.QuotaCode;
      obj.quotaName = e.QuotaName;
      // 定额取综合价
      obj.quotaPrice = e.QuotaPrice;
    }
    // @ts-expect-error
    budchgDetails.push(obj);
    setQuoteType(-1);
  };

  // 承担人弹窗
  const [undertakerModel, setUndertakerModel] = useState<Undertaker>();
  const pickerUnderTakerChange = (data, type) => {

    if (type === "supplier") {
      ["supplyId", "supplyName", "supplyCode"].forEach((key) => {
        undertakerModel!.type = 1;
        undertakerModel![key] = data[key];
      });
    } else if (type === "project") {
      undertakerModel!.type = 0;
      undertakerModel!.userId = data.userId;
      undertakerModel!.userCode = data.userCode;
      undertakerModel!.userName = data.userName;
    } else if (type === "erp") {
      undertakerModel!.type = 2;
      undertakerModel!.userId = data.user_id;
      undertakerModel!.userCode = data.user_code;
      undertakerModel!.userName = data.user_name;
    }

    setUndertakerModel(undefined);
  };

  // 统一关闭弹窗
  const popupClose = () => {
    setQuoteType(-1);
    setUndertakerModel(undefined);
  };

  // 获取审批流
  const [flowList] = useWorkflowDefinition({ typeCode: "FI_SignReport" })

  // 编辑模式：获取签报信息
  useFetch(ApiWorkflow.signReportDetail, {
    manual: !masterId,
    defaultParams: [
      {
        workFlowDefinitionId,
        masterId: masterId ? decodeURIComponent(masterId) : "",
      },
    ],
    onSuccess(res: any) {
      model.undertakers.length = 0;

      res.undertakers.forEach((e) => {
        model.undertakers.push(e);
      });


      res.details.forEach(element => {
        budchgDetails.push(element)
      });

      setModel({
        ...res,
        undertakers,
        files: res.files || [],
        budchgDetails,
      });
    },
  });

  // 编辑模式：获取审批流节点
  useFetch<TaskDetail>(ApiWorkflow.detail, {
    manual: !workflowInstanceId,
    defaultParams: [{ workflowInstanceId }],
    onSuccess(res) {
      setModel({
        workFlowDefinitionId: res.workflowDefinitionId,
      });
    },
  });

  const userInfo = useAppStore((state) => state.userInfo);
  const beforeSubmit = () => {
    const { type, amount, undertakers } = model;

    if (type === 2) {
      // 奖励
      undertakers.length = 0;
      undertakers.push({
        type: 0,
        amount,
        userId: userInfo.user_id,
        userCode: userInfo.user_code,
        userName: userInfo.user_name,
      });
    }

    submit({
      ...model,
      undertakers,
    });
  };

  const worflowIndex = flowList.findIndex(
    (e) => e.workflowDefinitionId == model.workFlowDefinitionId
  );

  const workflowSelected = flowList ? flowList[worflowIndex] : undefined;

  // 承担金额、定额/材料 计算小计金额
  const getsubtotal = () => {
    const taskerAmount = undertakers.reduce(
      (sum, item) => sum + (item.amount || 0),
      0
    );

    const budchgAmount = budchgDetails.reduce((sum, e) => {
      const amount = e.detailType
        ? (e.materialNum || 0) * e.materialSalePrice
        : e.quotaNum * e.quotaPrice;

      return sum + amount;
    }, 0);

    return {
      taskerAmount,
      budchgAmount,
    };
  };
  // const subtotal = getsubtotal();

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton
            size="large"
            loading={loading}
            className="w-2/3"
            onClick={beforeSubmit}
          >
            提交
          </ByButton>
        }
      >
        <CustomerCard source={data} />

        <View className="m-3">
          <ByCellGroup>
            <ByCell label="收支类型" requierd vertical>
              <TagRadioGroup
                options={enumReportTypeOptions}
                value={[model.type]}
                valueKey="value"
                onChange={([type]) => setModel({ type })}
              />
            </ByCell>
            {model.type === 1 ? (
              <ByCell label="阶段" requierd vertical>
                <TagRadioGroup
                  value={[model.penaltyType]}
                  options={[{ label: "中期款承担" }, { label: "尾款承担" }]}
                  onChange={([penaltyType]) => setModel({ penaltyType })}
                />
              </ByCell>
            ) : (
              <ByCell label="金额" vertical>
                <FormInputNumber
                  prefix="¥"
                  precision={2}
                  placeholder="输入金额"
                  defaultValue={model.amount}
                  onChange={(amount) => setModel({ amount })}
                />
              </ByCell>
            )}
          </ByCellGroup>

          {/* 惩罚才显示承担人 */}
          {model.type === 1 && (
            <ByCellGroup className="mt-3">
              {model.undertakers?.map((item, index) => (
                <UndertakersItem
                  key={item._id}
                  source={item}
                  showRemove={index != 0}
                  onPicker={setUndertakerModel}
                  onRemove={() => undertakers.splice(index, 1)}
                />
              ))}

              {/* <ByRow content="between" className="pb-3">
                <ByText size="sm" type="second">
                  小计：¥{subtotal?.taskerAmount}
                </ByText>

                <ByText
                  size="sm"
                  type="primary"
                  onClick={() => undertakers.push(createUndertaskerItem())}
                >
                  <ByIcon name="Plus" />
                  添加
                </ByText>
              </ByRow> */}

              <View className="pb-3">
                <ByText
                  size="sm"
                  type="primary"
                  onClick={() => undertakers.push(createUndertaskerItem())}
                >
                  <ByIcon name="Plus" />
                  添加
                </ByText>
              </View>
            </ByCellGroup>
          )}

          <ByCellGroup className="mt-5" title="定额、材料">
            {budchgDetails.length === 0 && (
              <View className="py-3 text-center">
                <ByText size="sm" type="third">
                  未添加定额或材料
                </ByText>
              </View>
            )}

            {model.budchgDetails?.map((item, index) => (
              <BudchgDetailsItem
                key={item._id}
                source={item}
                onRemove={() => budchgDetails.splice(index, 1)}
              />
            ))}

            {/* <ByRow content="between" className="py-3">
              <ByText size="sm" type="second">
                小计：¥{subtotal?.budchgAmount}
              </ByText>

              <ByText type="primary" size="sm" onClick={chooseQuoteType}>
                <ByIcon name="Plus" />
                添加
              </ByText>
            </ByRow> */}

            <View className="text-center py-3">
              <ByText type="primary" size="sm" onClick={chooseQuoteType}>
                <ByIcon name="Plus" />
                添加
              </ByText>
            </View>
          </ByCellGroup>

          <ByCellGroup className="mt-5">
            <ByCell label="特殊情况说明" vertical>
              <FormInput
                rows={5}
                type="textarea"
                value={model.description}
                placeholder="输入说明"
                onChange={(e) => setModel({ description: e })}
              />
            </ByCell>

            <ByCell label="备注" vertical>
              <FormInput
                rows={5}
                type="textarea"
                value={model.remark}
                placeholder="输入备注"
                onChange={(e) => setModel({ remark: e })}
              />
            </ByCell>

            <ByCell label="附件" vertical>
              <ByImageGroup
                showDelete
                urls={model.files}
                onChange={(files) => setModel({ files })}
                slotFooter={
                  <Uploader
                    size={140}
                    onSuccess={(res) =>
                      setModel({ files: model.files.concat(res) })
                    }
                  />
                }
              />
            </ByCell>
          </ByCellGroup>

          <ByCellGroup className="mt-5" title="审批">
            <ByCell label="选择审批流程" vertical requierd>
              <Picker
                range={flowList}
                disabled={!!masterId}
                rangeKey="workflowDefinitionName"
                value={worflowIndex}
                className="w-full"
                onChange={({ detail }) =>
                  setModel({
                    workFlowDefinitionId:
                      flowList[detail.value]["workflowDefinitionId"],
                  })
                }
              >
                <FormInput
                  disabled
                  placeholder="请选择"
                  value={workflowSelected?.workflowDefinitionName}
                  suffix={<ByIcon name="ArrowBottom" />}
                />
              </Picker>
            </ByCell>

            {workflowSelected?.steps.map((item) => (
              <ByStepsItem title={item.nodeName} key={item.nodeId}>
                <BySpace>
                  {item.approvers?.map((item) => (
                    <ByTag size="small" variant="outline" key={item.actorId}>
                      {item.actorName}
                    </ByTag>
                  ))}
                </BySpace>
              </ByStepsItem>
            ))}
          </ByCellGroup>
        </View>
      </Page>

      <PageContainer
        round
        show={!!undertakerModel || quoteType > -1}
        onLeave={popupClose}
      >
        {undertakerModel && (
          <PopupMember
            title="承担人"
            intentCustomerId={intentCustomerId}
            type={["erp", "supplier", "project"]}
            onCancel={popupClose}
            onConfirm={pickerUnderTakerChange}
          />
        )}

        {quoteType === 0 ? (
          <PopupQuota onChange={pickerQuotaChange} onCancel={popupClose} />
        ) : quoteType === 1 ? (
          <PopupShop
            from="report"
            intentCustomerId={intentCustomerId}
            onCancel={popupClose}
            onConfirm={pickerQuotaChange}
          />
        ) : null}
      </PageContainer>
    </>
  );
};
